<template>
<div class="ww">
    <h1>实时搜索</h1>
    <input v-model="search" placeholder="输入搜索内容...." />
    <p>搜索结果数量: {{  resultCount }}</p>
    <p>搜索结果: {{ resultMessage }}</p>
</div>
</template>

<script setup>
import { ref, watch } from 'vue'

const search = ref('')
const resultCount = ref(0)
const resultMessage = ref()

//模拟一个搜索函数
const searchResults = (term) => {
    //写搜索逻辑
    const allItems = ['小狗','小猫','大老鼠','蔡徐坤','李大大','王小小'];
    return allItems.filter(item => item.includes(term)) //获取到包含子字符串的值;filter()函数用于数组元素的筛选;includes()函数用于显示否存在某个字符串的元素
}

//侦听search的变化
watch(search,(newValue) => {
    resultMessage.value = searchResults(newValue); //调用searchResults函数搜索是否存在输入的字符串
    resultCount.value = resultMessage.value.length;
})

</script>

<style scoped>
.ww{
    background-color: rgb(238, 241, 255);
    border-radius: 10px;
    padding:20px;
}
</style>